package cn.edu.hyit.hjq.volunteems.backend.service.impl;

import cn.edu.hyit.hjq.volunteems.backend.mapper.ActivityMapper;
import cn.edu.hyit.hjq.volunteems.backend.mapper.RegistrationMapper;
import cn.edu.hyit.hjq.volunteems.backend.pojo.Activity;
import cn.edu.hyit.hjq.volunteems.backend.service.SmsReminderService;
import cn.edu.hyit.hjq.volunteems.backend.service.SmsService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class SmsReminderServiceImpl implements SmsReminderService {

    private final ActivityMapper activityMapper;
    private final RegistrationMapper registrationMapper;
    private final SmsService smsService;

    public SmsReminderServiceImpl(ActivityMapper activityMapper, RegistrationMapper registrationMapper, SmsService smsService) {
        this.activityMapper = activityMapper;
        this.registrationMapper = registrationMapper;
        this.smsService = smsService;
    }

    // 每小时执行一次
    @Scheduled(cron = "0 0 * * * ?")
    public void remindVolunteers() {
        LocalDateTime now = LocalDateTime.now();
        remindVolunteers(now);
    }

    @Override
    public void remindVolunteers(LocalDateTime now) {
        LocalDateTime oneHourLater = now.plusHours(1);
        List<Activity> upcoming = activityMapper.findActivitiesStartingAt(now, oneHourLater);

        for (Activity activity : upcoming) {
            List<String> phones = getVolunteerPhones(activity.getActivityId());
            for (String phone : phones) {
                String msg = "提醒：您报名的活动【" + activity.getTitle() + "】即将在1小时后开始，请按时签到。";
                smsService.send(phone, msg);
            }
        }
    }

    private List<String> getVolunteerPhones(Long activityId) {
        return registrationMapper.findVolunteerPhoneByActivityId(activityId);
    }
}
